﻿using RabbitMQ.Client;
using System.Text;

namespace RabbitMQDemo.Producer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start the producer");

            var connFactory = new ConnectionFactory
            {
                HostName = "106.53.127.56",
                Port = 5672,
                UserName = "rabbitmqdemo",
                Password = "rabbitmqdemo@test",
                VirtualHost = "rabbitmqdemo"
            };
            using (var conn = connFactory.CreateConnection())
            {
                using (var channel = conn.CreateModel())
                {
                    //延迟交换机
                    var delayExchangeName = "delay_exchange";
                    var delayArguments = new Dictionary<string, object>
                    {
                        { "x-delayed-type", "direct" } //x-delayed-type必须，否则启动报错
                    };
                    channel.ExchangeDeclare(exchange: delayExchangeName, type: "x-delayed-message", durable: true, autoDelete: false, arguments: delayArguments); //持久化必须，否则启动报错

                    //延迟队列
                    var delayQueueName = "delay_queue";
                    channel.QueueDeclare(delayQueueName, durable: true, exclusive: false, autoDelete: false);//持久化必须，否则启动报错
                    channel.QueueBind(queue: delayQueueName, exchange: delayExchangeName, routingKey: delayQueueName);

                    channel.BasicReturn += new EventHandler<RabbitMQ.Client.Events.BasicReturnEventArgs>((sender, e) =>
                    {
                        var message = Encoding.UTF8.GetString(e.Body.ToArray());
                        Console.WriteLine($"收到回退消息：{message}");
                    });

                    while (true)
                    {
                        Console.WriteLine("消息内容(exit退出):");
                        var message = Console.ReadLine();
                        if (message.Trim().ToLower() == "exit")
                        {
                            break;
                        }

                        var body = Encoding.UTF8.GetBytes(message);
                        var basicProperties = channel.CreateBasicProperties();
                        basicProperties.Headers = new Dictionary<string, object>
                        {
                            { "x-delay", message == "aaa"?30000:10000 }//延时时间从header赋值
                        };
                        //mandatory，官方不建议使用 https://github.com/rabbitmq/rabbitmq-delayed-message-exchange/issues/138
                        channel.BasicPublish(exchange: delayExchangeName, routingKey: delayQueueName, mandatory: true, basicProperties: basicProperties, body: body);
                        Console.WriteLine("消息内容发送完毕:" + message + $" {DateTime.Now}");
                    }
                }
            }
        }
    }
}